import torch
from torch import nn

"""
位置编码
"""


class PositionEncoding(nn.Module):
    def __init__(self, embedding_dims, max_len, dropout):
        super().__init__()

        self.dropout = nn.Dropout(dropout)
        self.P = torch.zeros((1, max_len, embedding_dims))
        d_model = embedding_dims

        x = torch.arange(max_len).unsqueeze(-1) / torch.pow(10000, torch.arange(0, embedding_dims, 2) / d_model)
        self.P[:, :, 0::2] = torch.sin(x)
        self.P[:, :, 1::2] = torch.cos(x)

    def forward(self, x):  # x是经过词嵌入之后的值。 (batch_size,seq_len,embedding_dims)
        seq_len = x.shape[1]
        pe = self.P[:, :seq_len, :]
        return self.dropout(x + pe)
